package com.hyc.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Slf4j
@Service
public class UploadService {
    private final static String CODE = "UTF-8";

    public String upload(MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return null;
        }

        String url = request.getRequestURL().toString();
        url = url.substring(0, url.indexOf("upload"));

        String filename = "";
        try {
            File path = new File(ResourceUtils.getURL("classpath:static/").getPath());
            File upload = new File(path.getAbsolutePath(), "upload/");
            if (!upload.exists()) {
                upload.mkdirs();
            }
            filename = System.currentTimeMillis() + file.getOriginalFilename();
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(upload, filename));
        } catch (Exception e) {
            log.error("文件上传异常", e);
        }

        url = url + "static/upload/" + filename;
        return url;
    }
}
